/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.resource.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.apache.commons.lang.time.DateFormatUtils;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.resource.client.FastDFSClient;
import org.springblade.resource.client.FastDFSException;
import org.springblade.resource.entity.Annexe;
import org.springblade.resource.mapper.AnnexeMapper;
import org.springblade.resource.service.IAnnexeService;
import org.springblade.resource.vo.AnnexeVO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 附件表 服务实现类
 *
 * @author BladeX
 * @since 2021-07-22
 */
@Service
public class AnnexeServiceImpl extends BaseServiceImpl<AnnexeMapper, Annexe> implements IAnnexeService {

	private FastDFSClient fastDFSClient = new FastDFSClient();

	/**
	 * 文件服务器地址
	 */
	@Value("${file_server_addr}")
	private String fileServerAddr;

	/**
	 * FastDFS秘钥
	 */
	@Value("${fastdfs.http_secret_key}")
	private String fastDFSHttpSecretKey;

	@Override
	public IPage<AnnexeVO> selectAnnexePage(IPage<AnnexeVO> page, AnnexeVO annexe) {
		return page.setRecords(baseMapper.selectAnnexePage(page, annexe));
	}

	@Override
	public List<Annexe> findList(Annexe annexe) {
		return baseMapper.findList(annexe);
	}

	@Override
	public boolean batchSave(String bizType, Long bizId, MultipartFile[] files)  {

		try {
			String yyyymm = DateFormatUtils.format(new Date(), "yyyyMM");
			List<Annexe> list = new ArrayList<>();
			for (int i = 0; i < files.length; i++) {
				MultipartFile multipartFile = files[i];
				//基础地址/bizType/yyyyMM/
				/// - 删除 zhangtao  String fileStoragePath = CommonConstant.BASE_FILE_PATH + File.separator + bizType + File.separator + yyyymm + File.separator;
				String fileType = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf(".") + 1);
				/// - 删除 zhangtao String fileStorageName = UUID.randomUUID().toString()+"."+fileType;
				Long size = multipartFile.getSize();
				String fileName = multipartFile.getOriginalFilename();

			/* - 删除 zhangtao File targetFile = new File(fileStoragePath, fileStorageName);
			// 创建文件夹
			if (!targetFile.getParentFile().exists()) {
				targetFile.getParentFile().mkdirs();
			}
			// 将上传文件存储到服务器中
			// multipartFile.transferTo(targetFile);
			*/

				// 上传到fastDFS服务器
				String fileStoragePath = fastDFSClient.uploadFileWithMultipart(multipartFile);

				// 设置访文件的Http地址. 有时效性.
				String fileStorageToken = FastDFSClient.getToken(fileStoragePath, fastDFSHttpSecretKey);

				//System.out.println("filepath: " + fileStoragePath  + " --- " + "token:" + fileStorageToken);

				Annexe annexe = new Annexe(bizType, bizId, fileName, fileStoragePath, fileStorageToken, fileType, size, "");
				list.add(annexe);
			}

			if (list.size() > 0) {
				super.saveBatch(list);
			}
		}catch(FastDFSException e){
			e.printStackTrace();
			return false;
		}catch (Exception e){
			e.printStackTrace();;
			return false;
		}

		return true;
	}

	@Override
	@Transactional
	public String saveForUrl(String bizType, Long bizId, MultipartFile multipartFile) throws IOException {
		String filePath = null;
		try {
			String yyyymm = DateFormatUtils.format(new Date(), "yyyyMM");
			//基础地址/bizType/yyyyMM/
			/// - 删除 zhangtao  String fileStoragePath = CommonConstant.BASE_FILE_PATH + File.separator + bizType + File.separator + yyyymm + File.separator;
			String fileType = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf(".") + 1);
			/// - 删除 zhangtao String fileStorageName = UUID.randomUUID().toString()+"."+fileType;
			Long size = multipartFile.getSize();
			String fileName = multipartFile.getOriginalFilename();

			// 上传到fastDFS服务器
			String fileStoragePath = fastDFSClient.uploadFileWithMultipart(multipartFile);

			// 设置访文件的Http地址. 有时效性.
			String fileStorageToken = FastDFSClient.getToken(fileStoragePath, fastDFSHttpSecretKey);

			//System.out.println("filepath: " + fileStoragePath  + " --- " + "token:" + fileStorageToken);

			Annexe annexe = new Annexe(bizType, bizId, fileName, fileStoragePath, fileStorageToken, fileType, size, "");
			return super.save(annexe)?fileStoragePath:null;
		}catch (Exception e){
			e.printStackTrace();;
			return null;
		}

		//return filePath;
	}

	@Override
	@Transactional
	public boolean remove(List<Long> idList) {
		List<Annexe> dataList = baseMapper.findListByIds(idList);
		baseMapper.remove(idList);

		for (int i = 0; i < dataList.size(); i++) {
			Annexe data = dataList.get(i);
			// FileUtils.deleteFile(data.getFileStoragePath() + data.getFileStorageName());
			try {
				fastDFSClient.deleteFile(data.getFileStoragePath());
			} catch (FastDFSException e) {
				e.printStackTrace();
				return false;
			}
		}

		return true;
	}

	@Override
	@Transactional
	public boolean copyAndOverwriteUpdate(String fromBizType, Long fromBizId, String toBizType, Long toBizId, boolean overwriteUpdate) {
		Annexe search = new Annexe();
		search.setBizId(fromBizId);
		search.setBizType(fromBizType);
		List<Annexe> dataList = baseMapper.findList(search);
		for (Annexe annexe : dataList) {
			annexe.setBizId(toBizId);
			annexe.setBizType(toBizType);
			annexe.setId(null);
		}
		if(overwriteUpdate){
			baseMapper.removeByBiz(toBizType,toBizId);
		}
		return super.saveBatch(dataList);
	}

	@Override
	public boolean removeByBizIdAndType(String bizType, Long bizId) {
		Annexe annexe=super.getOne(Wrappers.<Annexe>query().lambda().eq(Annexe::getBizId,bizId).eq(Annexe::getBizType,bizType));
		if(annexe.getFileStoragePath()!=null){
			try {
				fastDFSClient.deleteFile(annexe.getFileStoragePath());
			}catch (Exception e){
				e.printStackTrace();
			}
		}
		return super.removeById(annexe.getId());
	}

}
